#!/bin/bash
set -ex
REMOTEDIR=/ZSTP/basic_data
DATADIR=/home/work/changsha_project/basic_data

for ((i=1;i<=5;i++));
do
    cd ${DATADIR}
    file_date=`date -d "$i days ago" +%Y%m%d`
    for result in `ls | grep data_parsed_${file_date}_*.tgz | grep -v _bak`
    do

#        result="data_parsed_`date -d "$i days ago" +%Y%m%d`_23"
        if [ ! -e ${DATADIR}/${result} ]; then
            echo "data not ready: ${result}"
            continue
        fi

        DATE_FOLDER=`date -d "$i days ago" +%Y%m%d`
        echo "准备上传当前数据: ${result}"
        expect <<EOF
        set timeout -1

        spawn sftp haizhisftp@zstp.ibcs.cn
        expect "password:"
        send "Zstp@36:bcs\r"

        expect "sftp>"
        send "mkdir ${REMOTEDIR}/${DATE_FOLDER}\r"

        expect "sftp>"
        send "put ${DATADIR}/${result} ${REMOTEDIR}/${DATE_FOLDER}\r"

        expect "sftp>"
        send "quit\r"
        expect eof
EOF
        echo "完成数据传输没有异常退出.."
        cd ${DATADIR}
        rm -rf ${result}_bak
        mv ${result} ${result}_bak
        echo "备份数据完成..."
    done
done

echo "上传basic数据完成..."


for ((i=10;i<=30;i++));
do
    file_date=`date -d "$i days ago" +%Y%m%d`
    for result in `ls | grep data_parsed_${file_date}_*.tgz_bak`
    do
        if [ ! -e ${DATADIR}/${result} ]; then
            continue
        fi

        rm -rf ${DATADIR}/${result}
        echo "删除数据: ${result}"
    done
done

echo "删除basic历史数据完成..."